/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FrmCadastroConsulta.java
 *
 * Created on 30/11/2011, 03:02:06
 */
package com.pedagio.view;

import com.pedagio.dominio.Consulta;
import com.pedagio.modelo.ConsultaModelo;
import com.pedagio.negocio.ConsultaService;
import com.pedagio.negocio.UsuarioService;
import com.pedagio.dominio.Usuario;
import com.pedagio.util.Controle;
import java.awt.Color;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;

/**
 *
 * @author andregonzaga
 */
public class FrmCadastroConsulta extends javax.swing.JDialog {

    private ConsultaService consultaService = Controle.getConsultaService();
    private UsuarioService veiculoService = Controle.getUsuarioService();


    /** Creates new form FrmCadastroExame */
    public FrmCadastroConsulta(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        jLabel7.setText("");
        popularTabela();
        preencheComboVeiculos();
    }

    /**
     * Preenche combobox com lista de Veiculos cadastrados
     */
    private void popularListaVeiculo(JComboBox listaPlacas) {
        List<Usuario> veiculos = veiculoService.findAllUsuario();
        for (Usuario veiculo : veiculos) {
            listaPlacas.addItem(veiculo);
        }
    }

    /**
     * Remove os itens do combo de veiculos e chama o metodo que a popula
     */
    private void preencheComboVeiculos() {
        listaUsuarios.removeAllItems();
        popularListaVeiculo(listaUsuarios);
    }
    
    private void popularTabela() {
        
        ConsultaModelo consultaModelo = new ConsultaModelo();
        jTable2.setModel(consultaModelo);
        
        List<Consulta> consultas = consultaService.findAll();
        for (Consulta consulta : consultas) {
           consultaModelo.addRow(consulta);
        }
        
    }
    
    public void salvar() {
        
//        if(!validar()) {
//            return;
//        }
        
        Consulta consulta = new Consulta();

        consulta.setNome(jTextField1.getText());
        consulta.setTipo(jComboBox1.getSelectedItem().toString());
        consulta.setFormaPagamento(jComboBox2.getSelectedItem().toString());
        consulta.setHora(jTextField3.getText());
        consulta.setPaciente(listaUsuarios.getSelectedItem().toString());

        DateFormat date = new SimpleDateFormat("dd/MM/yyyy");
        Date validade;
        try {
            validade = date.parse(jTextField2.getText());
            consulta.setDataConsulta(validade);
        } catch (ParseException ex) {
            Logger.getLogger(FrmCadastroConsulta.class.getName()).log(Level.SEVERE, null, ex);
        }


            if (consulta.getTipo().toString() == "Cortesia") {
            Integer quantcortesia = 0;
            ArrayList<Consulta> newIterator = (ArrayList<Consulta>) consultaService.findAll();
            for (int a = 0; a < newIterator.size(); a++) {
                if (newIterator.get(a).getTipo().toString().equals("Cortesia"))
                    quantcortesia++;
            }
            if((quantcortesia % 5 == 0) && (quantcortesia>0)){
                jLabel7.setText("Nao autorizado");
                jLabel7.setBackground(Color.RED);
            }
            else{
                consultaService.persist(consulta);
                     jLabel7.setText("Autorizado");
                     jLabel7.setBackground(Color.GREEN);


            }
        }
        if (consulta.getTipo().toString() == "Particular") {
             if(consulta.getFormaPagamento().toString() == "Dinheiro"){
                consultaService.persist(consulta);
                     jLabel7.setText("Autorizado");
                     jLabel7.setBackground(Color.GREEN);

             }

             if(consulta.getFormaPagamento().toString() == "Cartao"){
                 consultaService.persist(consulta);
                     jLabel7.setText("Autorizado");
                     jLabel7.setBackground(Color.GREEN);
             }

             if(consulta.getFormaPagamento().toString() == "Cheque"){
                 Random random = new Random();
                 Integer i = random.nextInt();
                 if(i%2==0){
                     consultaService.persist(consulta);
                     jLabel7.setText("Autorizado");
                     jLabel7.setBackground(Color.GREEN);
                 }
                 else{
                    jLabel7.setText("Nao autorizado");
                    jLabel7.setBackground(Color.RED);
                 }
             }
        }
        if (consulta.getTipo().toString() == "Convenio") {
            consultaService.persist(consulta);
            jLabel7.setText("Autorizado");
            jLabel7.setBackground(Color.GREEN);

        }
        if (consulta.getTipo().toString() == "Retorno") {
            consultaService.persist(consulta);
            jLabel7.setText("Autorizado");
            jLabel7.setBackground(Color.GREEN);

        }


        
//        consultaService.persist(consulta);
  //      jLabel7.setText("Salvo com sucesso!");
    //    jLabel7.setBackground(Color.GREEN);
        
        popularTabela();
        limparDados();
    }
    
    public void excluir() {

         int selectedRows[] = jTable2.getSelectedRows();

        int size = selectedRows.length;

        if(size <= 0) {
            jLabel7.setText("Não ha consultas selecionadas.");
            jLabel7.setForeground(Color.yellow);
            return;
        }

        for (int i = size - 1; i >= 0; i--) {
            int row =  selectedRows[i];
            String usuarioId = (String) jTable2.getValueAt(row, 0);
            consultaService.delete(Long.parseLong(usuarioId));
            jLabel7.setText("Consulta(s) excluida(s) com sucesso.");
            jLabel7.setForeground(Color.BLUE);
        }

        popularTabela();
   }
    
    public void limparDados(){
        jTextField1.setText("");
        jTextField2.setText("");
        jTextField3.setText("");

        preencheComboVeiculos();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jLabel7 = new javax.swing.JLabel();
        listaUsuarios = new javax.swing.JComboBox();
        jComboBox1 = new javax.swing.JComboBox();
        jComboBox2 = new javax.swing.JComboBox();
        jButton2 = new javax.swing.JButton();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel1.setBackground(new java.awt.Color(242, 247, 247));

        jLabel1.setText("Agendamento de Consulta");

        jLabel2.setText("Nome medico:");

        jLabel3.setText("Data:");

        jLabel4.setText("Hora:");

        jLabel5.setText("Tipo Agendamento:");

        jLabel6.setText("Tipo Pagamento:");

        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        jButton1.setText("Salvar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable2.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
        jScrollPane2.setViewportView(jTable2);

        listaUsuarios.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        listaUsuarios.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                listaUsuariosActionPerformed(evt);
            }
        });

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Retorno", "Cortesia", "Particular", "Convenio" }));
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Dinheiro", "Cartao", "Cheque" }));
        jComboBox2.setEnabled(false);

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(382, 382, 382)
                        .add(jLabel7)
                        .addContainerGap())
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 532, Short.MAX_VALUE)
                        .add(9, 9, 9))
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(jButton1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 531, Short.MAX_VALUE)
                        .addContainerGap())
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                            .add(jPanel1Layout.createSequentialGroup()
                                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(jLabel4)
                                    .add(jLabel6)
                                    .add(jLabel5))
                                .add(185, 185, 185)
                                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(jComboBox2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                                        .add(org.jdesktop.layout.GroupLayout.LEADING, jComboBox1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                        .add(jTextField3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 184, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
                            .add(jPanel1Layout.createSequentialGroup()
                                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(jLabel2)
                                    .add(jLabel3))
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 280, Short.MAX_VALUE)
                                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                                    .add(jTextField2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 184, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                    .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 184, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
                        .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .add(listaUsuarios, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 141, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(jLabel1)
                        .addContainerGap(414, Short.MAX_VALUE))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel7)
                    .add(jLabel1))
                .add(35, 35, 35)
                .add(listaUsuarios, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(18, 18, 18)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel2)
                    .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jTextField2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel3))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jTextField3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel4))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel5)
                    .add(jComboBox1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel6)
                    .add(jComboBox2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(jButton1)
                .add(27, 27, 27)
                .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 101, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(212, 212, 212))
        );

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/btnExcluir.png"))); // NOI18N
        jButton2.setText("Exluir Itens Selecionados");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .add(layout.createSequentialGroup()
                .add(jButton2)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jButton2)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        salvar();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        excluir();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void listaUsuariosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_listaUsuariosActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_listaUsuariosActionPerformed

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1ActionPerformed

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        if (jComboBox1.getSelectedItem().toString() == "Particular") {
            jComboBox2.enable();
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_jComboBox1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                FrmCadastroConsulta dialog = new FrmCadastroConsulta(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBox2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JComboBox listaUsuarios;
    // End of variables declaration//GEN-END:variables
}
